package com.ybbase.framework.common.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 下载文件
 *
 * @author shenaiguo
 * @date 2014年12月23日
 * @since 4.0
 */
public class FileDownload {
    /**
     * UTF-8  字符集
     */
    private static final String CHARACTER_SET_UTF8 = "UTF-8";

    /**
     * 文件下载
     *
     * @param response 请求
     * @param filePath 文件完整路径(包括文件名和扩展名)
     * @param fileName 下载后看到的文件名
     * @author shenaiguo
     * @since 4.0
     */
    public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception {
        byte[] data = downloadWeb(filePath);
        fileName = URLEncoder.encode(fileName, CHARACTER_SET_UTF8);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", String.valueOf(data.length));
        response.setContentType("application/octet-stream;charset=" + CHARACTER_SET_UTF8);
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

    /**
     * 链接url下载图片
     *
     * @param urlList url链接
     * @return byte[] 数组
     * @author shenaiguo
     * @since 4.0
     */
    public static byte[] downloadWeb(String urlList) {
        URL url = null;
        byte[] context = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            context = output.toByteArray();
            dataInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return context;
    }
}
